<template>
    <div class="transactions-container">
        <h2>交易记录</h2>
        <div class="filter-bar">
            <div class="date-range">
                <span>时间范围：</span>
                <div class="date-inputs" v-if="dateRange === 'custom'">
                    <input type="date" v-model="customStartDate" @change="fetchTransactions">
                    <span>至</span>
                    <input type="date" v-model="customEndDate" @change="fetchTransactions">
                </div>
                <select v-else v-model="dateRange" @change="fetchTransactions">
                    <option value="7">最近7天</option>
                    <option value="30">最近30天</option>
                    <option value="90">最近3个月</option>
                    <option value="180">最近6个月</option>
                    <option value="custom">自定义范围</option>
                </select>
            </div>
            <button @click="fetchTransactions">刷新</button>
        </div>

        <div class="transactions-list" v-if="transactions.length > 0">
            <div class="transaction-item" v-for="(transaction, index) in transactions" :key="index">
                <div class="transaction-date">{{ transaction.date }}</div>
                <div class="transaction-info">
                    <div class="transaction-type" :class="transaction.type">{{ transaction.typeText }}</div>
                    <div class="transaction-desc">{{ transaction.description }}</div>
                </div>
                <div class="transaction-amount" :class="transaction.type">
                    {{ transaction.type === 'income' ? '+' : '-' }} ¥{{ transaction.amount.toFixed(2) }}
                </div>
            </div>
        </div>

        <div class="empty-state" v-else>
            <div class="empty-icon">📊</div>
            <div class="empty-text">暂无交易记录</div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'Transactions',
    data() {
        return {
            dateRange: '30',
            customStartDate: '',
            customEndDate: '',
            transactions: [],
            loading: false
        }
    },
    computed: {
        userInfo() {
            return this.$store.state.userInfo
        }
    },
    mounted() {
        this.fetchTransactions()
    },
    methods: {
        // 添加这些缺失的方法
        getTransactionType(item) {
            // 根据交易类型判断是收入还是支出
            const type = item.transactionType || '';
            if (type.includes('收入') || type.includes('转入') || type.includes('存款')) {
                return 'income';
            } else {
                return 'expense';
            }
        },

        getTransactionTypeText(item) {
            // 获取交易类型的显示文本
            const type = item.transactionType || '';
            if (type.includes('收入')) return '收入';
            if (type.includes('支出')) return '支出';
            if (type.includes('转入')) return '转入';
            if (type.includes('转出')) return '转出';
            return type;
        },

        parseAmount(amount) {
            // 解析金额为数字
            if (typeof amount === 'number') return amount;
            if (typeof amount === 'string') {
                return parseFloat(amount) || 0;
            }
            return 0;
        },

        fetchTransactions() {
            this.loading = true
            let startDate, endDate

            if (this.dateRange === 'custom') {
                if (!this.customStartDate || !this.customEndDate) {
                    this.$message.warning('请选择完整的日期范围')
                    this.loading = false
                    return
                }
                startDate = new Date(this.customStartDate)
                endDate = new Date(this.customEndDate)

                // 确保结束日期不早于开始日期
                if (endDate < startDate) {
                    this.$message.warning('结束日期不能早于开始日期')
                    this.loading = false
                    return
                }
            } else {
                endDate = new Date()
                startDate = new Date()
                startDate.setDate(endDate.getDate() - parseInt(this.dateRange))
            }

            const formatDate = (date) => {
                const year = date.getFullYear()
                const month = String(date.getMonth() + 1).padStart(2, '0')
                const day = String(date.getDate()).padStart(2, '0')
                return `${year}-${month}-${day}`
            }

            const params = {
                cardno: this.userInfo.cardno,
                pageNo: 1,
                pageSize: 10,
                startTime: formatDate(startDate),
                endTime: formatDate(endDate)
            }

            this.$axios({
                method: 'get',
                url: '/bank/page',
                params: params,
                timeout: 10000,  // 增加超时时间到10秒
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    console.log('API返回数据:', response.data); // 调试日志
                    if (response.data) {
                        // 检查返回的数据结构
                        const list = Array.isArray(response.data) ? response.data : 
                                    (response.data.list || response.data.data || []);
                        
                        this.transactions = list.map(item => ({
                            date: new Date(item.transactionDate).toLocaleDateString(),
                            type: this.getTransactionType(item),
                            typeText: this.getTransactionTypeText(item),
                            description: item.remark || '交易',
                            amount: this.parseAmount(item.amount)
                        }));
                    } else {
                        this.transactions = [];
                        console.log('没有交易记录');
                    }
                })
                .catch(error => {
                    console.error('获取交易记录失败:', error);
                    let errorMsg = '获取交易记录失败，请稍后重试';
                    if (error.code === 'ECONNABORTED') {
                        errorMsg = '请求超时，请检查网络连接';
                    } else if (error.response && error.response.data && error.response.data.msg) {
                        errorMsg = error.response.data.msg;
                    }
                    this.$message.error(errorMsg);
                    this.transactions = [];
                })
                .finally(() => {
                    this.loading = false;
                });
        }
    }
}
</script>

<style scoped>
/* 添加在每个组件的 style 标签内的开头 */
* {
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
}

input, 
button, 
select, 
textarea {
    user-select: text;
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    cursor: pointer;
}

input, 
textarea {
    cursor: text;
}
.transactions-container {
    padding: 30px;
    max-width: 1000px;
    margin: 0 auto;
}

h2 {
    color: #2c3e50;
    font-size: 28px;
    margin-bottom: 30px;
    text-align: center;
}

.filter-bar {
    background: white;
    border-radius: 15px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.date-range select,
.date-inputs input[type="date"] {
    padding: 10px 15px;
    border: 2px solid #eee;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.date-range select:focus,
.date-inputs input[type="date"]:focus {
    border-color: #409EFF;
    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.transaction-item {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease;
}

.transaction-item:hover {
    transform: translateX(5px);
}

.transaction-date {
    font-size: 14px;
    color: #909399;
    font-weight: 500;
}

.transaction-type {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 500;
}

.transaction-type.income {
    background: #f0f9eb;
    color: #67c23a;
}

.transaction-type.expense {
    background: #fef0f0;
    color: #f56c6c;
}

.transaction-amount {
    font-size: 18px;
    font-weight: 600;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 20px;
    color: #909399;
}

.empty-text {
    color: #606266;
    font-size: 16px;
}
</style>